package com.cloud.async.result.core.body;

import com.cloud.async.util.ex.AsyncException;

/**
 * 返回结果提Body
 *
 * @param <T>
 */
public class ResultBody<T> {

    /**
     * 类型信息
     */
    private final Class<T> responseType;
    /**
     * 实际结果
     */
    private final T result;
    /**
     * 错误信息（可选）
     */
    private final String errorMsg;

    /**
     * 执行时的时间戳（毫秒）
     */
    private final long executionTimestamp;

    /**
     * 当前时间戳（毫秒）
     */
    private final long currentTimestamp;

    // 成功情况的构造函数
    public ResultBody(Class<T> responseType, T result, long executionTimestamp, long currentTimestamp) {
        this.responseType = responseType;
        this.result = result;
        this.errorMsg = null;
        this.executionTimestamp = executionTimestamp;
        this.currentTimestamp = currentTimestamp;
    }

    // 失败情况的构造函数
    public ResultBody(Class<T> responseType, long executionTimestamp, long currentTimestamp, String errorMsg) {
        this.responseType = responseType;
        this.result = null;
        this.errorMsg = errorMsg;
        this.executionTimestamp = executionTimestamp;
        this.currentTimestamp = currentTimestamp;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public T getResult() {
        return result;
    }


    public T getResult(boolean tro) {
        if (tro && !isSuccess()) {
            throw new AsyncException("Failed to get result: operation marked as success-required but result indicates failure");
        }
        return result;
    }



    public Class<T> getResponseType() {
        return responseType;
    }

    public long getCurrentTimestamp() {
        return currentTimestamp;
    }

    public long getExecutionTimestamp() {
        return executionTimestamp;
    }

    // 判断是否成功
    public boolean isSuccess() {
        return result != null && errorMsg == null;
    }
}
